#!/bin/bash

if [ $# -lt 1 ]; then
   echo "Usage: $0 <repo list file>"
   exit 1
fi

LIST=$1
TOPDIR=/home/hitmoon/REPO

[ ! -d "$TOPDIR" ] && mkdir "$TOPDIR"
pushd "$TOPDIR" &>/dev/null


while read i
do
	repo=$(basename $i)

	echo "#################################################################"
	if [ ! -d "$repo" ]; then
	  echo "repo $repo not exist, cloning ..."
	  git clone "$i"
	else
	  echo "repo $repo already exist, go ahead."
	fi

	if [ ! -d "$repo" ]; then
	  echo "clone $repo failed, skip"
	  continue
	fi

        pushd $repo &>/dev/null
	echo "setting up to track all origin remote branch ..."
	git branch -r | grep -v '\->' | grep ' *origin/' | while read remote
	do
	  b=${remote#origin/}
	  git branch | grep -q "$b"
	  if [ "$?" -ne 0 ]; then
		git branch -t "$b" "$remote"
	  fi
	done

	echo "fetching all changes ..."
	git fetch origin

	echo "pull changes to local branch ..."
	git pull origin

	# create backup repo
	../git_create_repo.exp $repo

	# set up backup remote
	git branch -r | grep -q ' *backup/'
	if [ "$?" -ne 0 ]; then
	  echo "setting up backup remote ..."
	  git remote add backup ssh://hitmoon@192.168.0.114/volume1/git_repo/$repo
	fi
	set -e
	echo "pushing up to bakcup ..."
	../git_push.exp
	popd  &>/dev/null
	set +e
        echo "repo $repo backup done!"
	echo "#################################################################"
	echo ""

done < $LIST

popd &>/dev/null
python send_mail.py -m <smtp server> -u <user> -p <passwd> -F <your email>  -t <dest email> -s "sync_repo.sh: All your git repo has bacup successfully!

exit 0
